package cj.web.marry.controllers;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import cj.utils.Constants;
import cj.utils.ImageUtils;
import cj.utils.ReadConfigProperties;
import cj.utils.ReturnUUID;
import cj.utils.weixin.HttpsWenXinUtil;
import cj.web.BaseController;
import cj.web.marriage.constants.MarriageRegStatusEnum;
import cj.web.marriage.constants.RegAddressEnum;
import cj.web.marry.constants.MarriageInterestingEnum;
import cj.web.marry.dao.MarryTJDAO;
import cj.web.marry.dao.UserApplicationDAO;
import cj.web.marry.utils.ImageCropper;
import cj.web.marry.utils.ImagePic;
import cj.web.marry.utils.ImagePicture;

/**
 * 结婚提交
 * @author Administrator
 *
 */
@Path("marrytj")
public class MarryTJController extends BaseController{
	
	protected static final Log logger = LogFactory.getLog(MarryTJController.class); 
	
	public final static String image_jpg=".jpg";
	
	public final static String image_png=".png";
	
	@Autowired
	private MarryTJDAO marryTJDao;
	
	@Autowired
	private UserApplicationDAO userApplicationDao;
	
	@Get("main")  
	public String main(){
		return "r:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb8851d53461b983d&redirect_uri=http://marriage.haoyicn.cn/marrytj/tjCode&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
	}
	
	/**
	 * 婚典信息提交
	 * @param model
	 * @param code
	 * @param response
	 * @return
	 */
	@Get("tjCode")  
	public String homeCode(Model model,@Param("code")String code, HttpServletResponse response){
		String openId = HttpsWenXinUtil.retOpenId(code,Constants.weixinkey.AppID,Constants.weixinkey.AppSecret);
//		String openId = "ofwuNs6UmiRLwJOVyhwagNTJ8p2Y";
		setCookie(response, "openId", openId);
		
		List<Map> reps = marryTJDao.getMarriageTJListByOpenid(openId);
		//判断是否提交记录
		if(reps!=null && reps.size()>0){
			//提交业务ID
			int id = Integer.parseInt(reps.get(0).get("id").toString());
			//图片
			String hash = reps.get(0).get("hash")==null?"":reps.get(0).get("hash").toString();
			if(hash==null || "".equals(hash)){
				//不存在图片去选择上头条
				return "r:headline?id="+id;
			}
			//存在图片去最后一页
			return "r:photo?id="+id;
		}
			
		return "r:show";
	}
	
	/**
	 * 提交页面1
	 * @param model
	 * @return
	 */
	@Get("show")
	public String show(Model model, HttpServletRequest request){
		String openId = getCookieValueByName(request, "openId");
		
		List<Map> userObj = userApplicationDao.queryByOpenId(openId);
		if(userObj!=null && userObj.size()>0){
			String code = userObj.get(0).get("id").toString();
			model.add("code", code);
		}else{
			model.add("code", "0000000");
		}
		
		model.add("openId", openId);
		model.add("AddressEnum", EnumSet.allOf(RegAddressEnum.class));
		model.add("InterestingEnum", EnumSet.allOf(MarriageInterestingEnum.class));
		return "/views/marry/marryTJDetail.vm";
	}
	
	/**
	 * 提交页面1
	 * @param model
	 * @return
	 */
	@Get("showReturn")
	public String showReturn(Model model, HttpServletRequest request,@Param("id")int id){
		List<Map> reps = marryTJDao.getMarriageTJList(id);
		
		if(reps!=null && reps.size()>0){
			String openid = reps.get(0).get("openid").toString();
			
			List<Map> userObj = userApplicationDao.queryByOpenId(openid);
			if(userObj!=null && userObj.size()>0){
				String code = userObj.get(0).get("id").toString();
				model.add("code", code);
			}else{
				model.add("code", "0000000");
			}
			
			model.add("openId", openid);
			model.add("AddressEnum", EnumSet.allOf(RegAddressEnum.class));
			model.add("InterestingEnum", EnumSet.allOf(MarriageInterestingEnum.class));
		}
		
		return "/views/marry/marryTJDetail.vm";
	}
	
	/**
	 * 提交操作
	 * @param man			男方姓名
	 * @param manPhone		男方电话
	 * @param woman			女方姓名
	 * @param womanPhone	女方电话
	 * @return
	 */
	@Post("submit")
	public String submit(@Param("code")String code,@Param("man")String man, @Param("manPhone")String manPhone, 
			@Param("woman")String woman, @Param("womanPhone")String womanPhone,@Param("addressId")String addressId,
			@Param("interestings")String interestings,@Param("openId")String openId){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		//分别验证男女是否重复，同时防止双方身份证号写反
		int size = marryTJDao.marryTjCount(code,man, manPhone, woman, womanPhone, interestings);
		
		if (size>0) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
			return "@" + jo.toString();
		}
		
		int status = MarriageRegStatusEnum.yuyue.getValue();
		try {
			List<Map> reps = marryTJDao.getMarriageTJListByOpenid(openId);
			if(reps!=null && reps.size()>0){
				//修改
				marryTJDao.update(code, man, manPhone, woman, womanPhone, addressId, interestings, openId);
				jo.put("id", reps.get(0).get("id"));
			}else{
				//新建
				int id = marryTJDao.create(code,man, manPhone, woman, womanPhone, status, addressId, interestings, openId);
				jo.put("id", id);
			}
			
		} catch (Exception e) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}

		return "@" + jo.toString();
	}
	
	/**
	 * 选择号外界面2
	 * @param model
	 * @param id
	 * @return
	 */
	@Get("headline")
	public String showheadline(Model model,@Param("id")String id){
		model.add("id", id);
		return "/views/marry/headline/headline.vm";
	}
	
	/**
	 * 号外生成2——————接收图片
	 * @param files
	 * @param id
	 * @param request
	 * @return
	 */
	@Post("updatePhoto")
    public String updatePhoto(@Param("uploadimage") MultipartFile[] files,@Param("id")int id,@Param("degree")int degree,HttpServletRequest request) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
    	String path = ReadConfigProperties.getValue("uploadFilePath");// 文件保存路径  
		
		// 判断文件列表是否为空  
        if (files != null && files.length > 0) {
        	for(MultipartFile file : files){
        		try {  
	            	//判断文件是否存在，不存在创建文件
	            	Map rep = ReturnUUID.getFolder(path);
	            	
	            	//所在的全路径
	            	path = rep.get("allpath").toString();
	            	
	            	//文件名
	                String fileName =  ReturnUUID.getUUID(); 
	                
	                //统一转换为JPG
	                String newFileName = fileName+image_jpg;
	                
	                //转存文件  
	                file.transferTo(new File(path+"/"+newFileName));  
	                
	                String returnImgPath = "";
	                
	                if(90==degree){
	                	//反转
	                	
	                	//上传得图片
		                BufferedImage bi = ImageIO.read(new File(path+"/"+newFileName));
		                //翻转90度
		        		BufferedImage newsImage = ImagePicture.rotateImage(bi);
		        		//统一转换为PNG
		                String newFileName_png = fileName+image_png;
		                //图片反转另存PNG
		        		ImageIO.write(newsImage, "png", new File(path+"/"+newFileName_png));
		        		
		        		ImageUtils.scale3(path+"/"+newFileName_png, path+"/y_"+newFileName_png, 840, 721);// 按比例压缩,做适当截取
		        		
		        		returnImgPath = ImageOp(path, id, "y_"+newFileName_png, rep.get("filepath").toString());
	                }else{
	                	//正常
	                	//JSON 文件路径
//		                jo.put("filePath", rep.get("filepath")+"/"+newFileName);
	                	
	                	ImageUtils.scale3(path+"/"+newFileName, path+"/y_"+newFileName, 840, 721);// 按比例压缩,做适当截取
	                	
		                returnImgPath = ImageOp(path, id, "y_"+newFileName, rep.get("filepath").toString());
	                }
	                
	                jo.put("id", id);
	                jo.put("returnImgPath", returnImgPath);
	                
	                marryTJDao.update(id, returnImgPath);
	                
                } catch (Exception e) {  
                    e.printStackTrace();  
                    jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
                }  
        	}
        } 
		
		return "@"+jo.toString();
    }
	
	/**
	 * 号外生成2——————接收图片base64
	 * @param files
	 * @param id
	 * @param request
	 * @return
	 */
	@Post("updatePhotoBase64")
    public String updatePhotoBase64(@Param("uploadimage") String filesBase64,@Param("id")int id,HttpServletRequest request) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
    	String path = ReadConfigProperties.getValue("uploadFilePath");// 文件保存路径  
		
		// 判断文件列表是否为空  
        if (filesBase64 != null && filesBase64.length() > 0) {
    		try {  
            	//判断文件是否存在，不存在创建文件
            	Map rep = ReturnUUID.getFolder(path);
            	
            	//所在的全路径
            	path = rep.get("allpath").toString();
            	
            	//文件名
                String fileName =  ReturnUUID.getUUID(); 
                
                //统一转换为JPG
                String newFileName = fileName+image_jpg;
                
                ImageCropper.generateImage(filesBase64.replace("data:image/jpeg;base64,", ""), path+"/"+newFileName);
                
                //JSON 文件路径
                String returnImgPath = ImageOp(path, id, newFileName, rep.get("filepath").toString());
                
                jo.put("id", id);
                jo.put("returnImgPath", returnImgPath);
                
                marryTJDao.update(id, returnImgPath);
                
            } catch (Exception e) {  
                e.printStackTrace();  
                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
            }  
        } 
		
		return "@"+jo.toString();
    }
	
	/**
	 * 合成图片方法
	 * @param filePath		图片路径
	 * @param id			TJ Id
	 * @param newFileName	新文件名
	 * @return
	 */
	private String ImageOp(String filePath,int id,String newFileName,String newPath){
		String templatePath = ReadConfigProperties.getValue("uploadFilePath")+"/template.jpg";
		//模版文件
		File file1 = new File(templatePath);  
		//待合成文件
        File file2 = new File(filePath,"/"+newFileName);  
        
        List<Map> replis = marryTJDao.getMarriageTJList(id);
        
        String returnImagePath = "";
        
        if(replis!=null && replis.size()>0){
        	Map rep = replis.get(0);
        	String man = rep.get("man").toString();
        	String woman = rep.get("woman").toString();
        	
        	String content = man+" "+woman+"结婚啦";
        	String fileName = "h_"+newFileName;
            
            try {
            	ImagePic.mergeImage(filePath,file1, file2,content,fileName); 
            	
            	returnImagePath=newPath+"/"+fileName;
            	
    		} catch (Exception e) {
    			// TODO: handle exception
    			e.printStackTrace();
    		}
             
        }
        
		return returnImagePath;
	}
	
	/**
	 * 号外展示3
	 * @param model
	 * @param id
	 * @return
	 */
	@Get("photo")
	public String showPhoto(Model model,@Param("id")int id){
		List<Map> replis = marryTJDao.getMarriageTJList(id);
		if(replis!=null && replis.size()>0){
			Map rep = replis.get(0);
			model.add("id", id);
			model.add("hash", rep.get("hash").toString());
		}
		
		return "/views/marry/headline/photo.vm";
	}
	
	@Get("tjSuccess")
	public String success(){
		return "/views/marry/tjSuccess.vm";
	}
	
	//----------------------Search 广告机打印
	@Get("search")
	public String search(Model model){
		model.add("AddressEnum", EnumSet.allOf(RegAddressEnum.class));
		return "/views/marry/search/search.vm";
	}
	
	/**
	 * 获取提交信息列表
	 * @param addressId	地址ID
	 * @param phone		电话
	 * @return
	 */
	@Get("getList")
	public String queryList(@Param("addressId")int addressId,@Param("phone")String phone) {
		
		JSONObject jo = new JSONObject();
		List<Map> objs = marryTJDao.getMarriageTJListByPhone(addressId, phone);
		
		for(Map obj:objs){
			String interesting = obj.get("interesting").toString();
			if(interesting==null || "".equals(interesting)){
				obj.put("interestingDesc", "");
			}else{
				String interestingDesc = "";
				int size = interesting.split(";").length;
				for(int i=0;i<size;i++){
					interestingDesc+=MarriageInterestingEnum.getName(
							Integer.parseInt(interesting.split(";")[i].toString()))+"｜";
					obj.put("interestingDesc", interestingDesc);
				}
			}
		}
		
		jo.put("data", objs);
		return "@"+jo.toString();
	}
}